<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { user } from "@/store/index.js";
import { homeGetArticleList } from "@/api/article";
import { homeGetConfig } from "@/api/config";
import { getAllTag } from "@/api/tag";
import { homeGetStatistic } from "@/api/home";
import { randomFontColor, numberFormate } from "@/utils/tool";
import PageHeader from "@/components/PageHeader/index.vue";
import HomeArticleList from "@/components/HomeArticle/home-article-list.vue";
import RightSide from "@/components/RightSide/right-side.vue";
import MobileTopSkeleton from "@/components/RightSide/components/skeleton/mobile-top-skeleton.vue";
import RightSideItem from "@/components/RightSide/components/item/right-side-item.vue";
import RightSideTop from "@/components/RightSide/components/item/right-side-top.vue";
import RightSideSkeletonItem from "@/components/RightSide/components/skeleton/right-side-skeleton-item.vue";
import { gsapTransY } from "@/utils/transform";

const userStore = user();

/** 文章 */
const param = reactive({
  current: 1, // 当前页
  size: 5, // 每页条目数
  loading: true, // 加载
});
const articleList = ref([]);
const articleTotal = ref();

const getHomeArticleList = async () => {
  try {
    let res = await homeGetArticleList(param.current, param.size);
    if (res.code == 0) {
      const { list, total } = res.result;
      articleList.value = list;
      articleTotal.value = total;
    }
  } finally {
    param.loading = false;
  }
};

const pagination = (page) => {
  param.current = page.current;
  getHomeArticleList();
};

/** 网站右侧 */
const rightSizeLoading = ref(false);
const runtime = ref(0);
let configDetail = ref({});
let tags = ref([]);

// 获取网站详细信息
const getConfigDetail = async () => {
  try {
    let res = await homeGetConfig();
    if (res.code == 0 && typeof res.result != "string") {
      configDetail.value = res.result;
      userStore.setBlogAvatar(res.result.blog_avatar);
      calcRuntimeDays(configDetail.value.createdAt);
    }
  } finally {
    rightSizeLoading.value = false;
  }
};

// 获取文章数、分类数、标签数
const getStatistic = async () => {
  let res = await homeGetStatistic();
  if (res.code == 0) {
    Object.assign(configDetail.value, res.result);
  }
};

// 获取所有的标签
const getAllTags = async () => {
  let res = await getAllTag();
  if (res.code == 0) {
    tags.value = res.result.map((r) => {
      r.color = randomFontColor();
      return r;
    });
  }
};

// 计算出网站运行天数
const calcRuntimeDays = (time) => {
  if (time) {
    // eslint-disable-next-line
    time = time.replace(/\-/g, "/"); // 解决ios系统上格式化时间出现NAN的bug
    const now = new Date().getTime();
    const created = new Date(time).getTime();
    const days = Math.floor((now - created) / 8.64e7);
    runtime.value = days;
  }
};

// 天气数据
const weatherData = ref({
  city: '',
  temperature: '',
  type: '',
  date: '',
  week: ''
});

// 获取天气信息的函数
const getWeatherInfo = async () => {
  try {
    const response = await fetch("https://api.vvhan.com/api/weather");
    const data = await response.json();
    if (data.success) {
      weatherData.value = {
        city: data.city,
        temperature: `${data.data.low}-${data.data.high}`,
        type: data.data.type,
        date: data.data.date,
        week: data.data.week
      };
    }
  } catch (error) {
    console.error("获取天气信息失败", error);
  }
};

const init = async () => {
  param.loading = true;
  rightSizeLoading.value = true;
  await getHomeArticleList("init");
  await getConfigDetail();
  await getStatistic();
  await getAllTags();
  await getWeatherInfo(); // 获取天气信息
};

const observeMobileBox = () => {
  nextTick(() => {
    gsapTransY([".mobile-top-card", ".mobile-bottom-card"], -30, 0.3, "bounce.in");
    gsapTransY([".mobile-bottom-card"], 30, 0.3, "none");
  });
};

// 判断是否为夜间模式
const isNightMode = computed(() => {
  const currentHour = new Date().getHours();
  return currentHour >= 18 || currentHour < 6;
});

// 新增：控制显示选项
const isConfigOpen = ref(false);
const showFPS = ref(true);
const showWeather = ref(true);
const showDate = ref(true);
const showTemperature = ref(true);
const showWeek = ref(true);

// 新增：FPS计算
const fps = ref(0);
let frameCount = 0;
let lastTime = 0;

const updateFPS = (time) => {
  if (lastTime === 0) {
    lastTime = time;
    requestAnimationFrame(updateFPS);
    return;
  }

  const delta = time - lastTime;
  frameCount++;

  if (delta > 1000) {
    fps.value = Math.round((frameCount * 1000) / delta);
    frameCount = 0;
    lastTime = time;
  }

  requestAnimationFrame(updateFPS);
};

onMounted(async () => {
  await init();
  await observeMobileBox();
  requestAnimationFrame(updateFPS);
});
</script>

<template>
  <PageHeader />
  <div class="home_center_box">
    <el-row>
      <el-col :xs="24" :sm="18">
        <!-- 修改：欢迎卡片，包含天气信息和新功能 -->
        <el-card
            class="welcome-card mobile-card info-card animate__animated animate__fadeIn"
            :class="{ 'night-mode': isNightMode }"
            shadow="hover"
        >
          <div class="welcome-content">
            <!-- 新增：FPS显示 -->
            <div v-if="showFPS" class="fps-display">
              FPS: {{ fps }}
            </div>

            <!-- 新增：配置开关 -->
            <el-switch
                v-model="isConfigOpen"
                class="config-switch"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>

            <!-- 配置面板 -->
            <div v-if="isConfigOpen" class="config-panel">
              <el-checkbox v-model="showFPS">显示 FPS</el-checkbox>
              <el-checkbox v-model="showWeather">显示天气</el-checkbox>
              <el-checkbox v-model="showDate">显示日期</el-checkbox>
              <el-checkbox v-model="showTemperature">显示温度</el-checkbox>
              <el-checkbox v-model="showWeek">显示星期</el-checkbox>
            </div>

            <!-- 欢迎信息 -->
            <template v-else>
              <h2 class="greeting">🎉 欢迎来自 <span class="highlight" style="color: red">{{ weatherData.city }}</span> 的小伙伴！</h2>
              <div class="info-container">
                <div v-if="showTemperature" class="info-item">
                  <i class="el-icon-sunny"></i>
                  <span>今日温度：<span class="highlight" style="color:red">{{ weatherData.temperature }}</span></span>
                </div>
                <div v-if="showWeather" class="info-item">
                  <i class="el-icon-cloudy"></i>
                  <span>天气：<span class="highlight" style="color:red">{{ weatherData.type }}</span></span>
                </div>
                <div v-if="showDate" class="info-item">
                  <i class="el-icon-date"></i>
                  <span>日期：<span class="highlight" style="color:red">{{ weatherData.date }}</span></span>
                </div>
                <div v-if="showWeek" class="info-item">
                  <i class="el-icon-calendar"></i>
                  <span>星期：<span class="highlight" style="color:red">{{ weatherData.week }}</span></span>
                </div>
              </div>
            </template>
          </div>
        </el-card>

        <!-- 其他卡片内容保持不变 -->
        <el-card
            class="mobile-top-card mobile-card info-card animate__animated animate__fadeIn"
            shadow="hover"
        >
          <el-skeleton :loading="rightSizeLoading" animated>
            <template #template>
              <MobileTopSkeleton />
            </template>
            <template #default>
              <RightSideTop :configDetail="configDetail" />
            </template>
          </el-skeleton>
        </el-card>
        <!-- 博客文章 -->
        <HomeArticleList
            :articleList="articleList"
            :param="param"
            :articleTotal="articleTotal"
            @pageChange="pagination"
        ></HomeArticleList>
        <el-card
            class="mobile-bottom-card card-hover mobile-card info-card animate__animated animate__fadeIn"
            shadow="hover"
        >
          <el-skeleton :loading="rightSizeLoading" animated>
            <template #template>
              <RightSideSkeletonItem />
            </template>
            <template #default>
              <RightSideItem icon="icon-zixun" size="1.4rem" title="网站资讯">
                <div class="site-info">
                  <div class="flex_r_between">
                    <span>文章数目：</span>
                    <span class="value">{{ configDetail.articleCount }}</span>
                  </div>
                  <div class="flex_r_between">
                    <span>运行时间：</span>
                    <span class="value">{{ runtime }} 天</span>
                  </div>
                  <div class="flex_r_between">
                    <span>博客访问次数：</span>
                    <span class="value">{{ numberFormate(configDetail.view_time) }}</span>
                  </div>
                  <div class="group">
                    交流群
                    <div class="flex justify-end items-start flex-nowrap">
                      <div v-image="configDetail.qq_group">
                        <el-image
                            class="img !ml-[10px]"
                            :src="configDetail.qq_group"
                            fit="cover"
                            :preview-src-list="[configDetail.qq_group]"
                            preview-teleported
                            lazy
                        >
                          <template #error>
                            <div class="w-[100%] h-[100%] grid place-items-center">
                              <svg-icon name="image404" :width="4" :height="4"></svg-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                      <div v-image="configDetail.we_chat_group">
                        <el-image
                            class="img"
                            :src="configDetail.we_chat_group"
                            fit="cover"
                            :preview-src-list="[configDetail.we_chat_group]"
                            preview-teleported
                            lazy
                        >
                          <template #error>
                            <div class="w-[100%] h-[100%] grid place-items-center">
                              <svg-icon name="image404" :width="4" :height="4"></svg-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                    </div>
                  </div>
                </div>
              </RightSideItem>
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col :xs="0" :sm="6">
        <!-- 博客我的信息 -->
        <RightSide
            :configDetail="configDetail"
            :tags="tags"
            :runtime="runtime"
            :loading="rightSizeLoading"
        />
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
:root {
  --day-bg: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  --night-bg: linear-gradient(135deg, #2c3e50 0%, #4ca1af 100%);
  --day-text: #333;
  --night-text: #fff;
  --day-highlight: #ff4757;
  --night-highlight: #ffa502;
  --day-shadow: rgba(0, 0, 0, 0.1);
  --night-shadow: rgba(255, 255, 255, 0.1);
}

.welcome-card {
  margin: 4px;
  padding: 1.5rem;
  border-radius: 12px;
  text-align: center;
  font-size: 1.1rem;
  transition: all 0.3s ease;
  background: var(--day-bg);
  color: var(--day-text);
  box-shadow: 0 4px 6px var(--day-shadow);
  transform: translateY(0);
  position: relative;

  &:hover {
    transform: translateY(-10px);
    box-shadow: 0 10px 20px var(--day-shadow);
  }

  &.night-mode {
    background: var(--night-bg);
    color: var(--night-text);
    box-shadow: 0 4px 6px var(--night-shadow);

    &:hover {
      box-shadow: 0 10px 20px var(--night-shadow);
    }

    .highlight {
      color: var(--night-highlight);
    }
  }

  .welcome-content {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .greeting {
    font-size: 1.5rem;
    margin: 0;
    font-weight: bold;
  }

  .highlight {
    color: var(--day-highlight);
    font-weight: bold;
  }

  .info-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 1rem;
  }

  .info-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;

    i {
      font-size: 1.2rem;
    }
  }

  .fps-display {
    position: absolute;
    top: 0.5rem;
    left: 0.5rem;
    font-size: 0.9rem;
    font-weight: bold;
  }

  .config-switch {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
  }

  .config-panel {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}

.mobile-top-card {
  height: 31rem;
  margin: 4px;
  :deep(.info-avatar) {
    padding: 0 2rem;
  }
  :deep(.personal-say) {
    padding-left: 1rem;
  }
  :deep(.info-background) {
    height: 12rem;
    width: 100%;
  }
  :deep(.common-menu) {
    padding: 1rem 5.5rem;
  }
  :deep(.git-ee) {
    padding: 0 4rem;
  }
  :deep(.personal-link) {
    padding: 1rem 6rem;
  }
}
.mobile-bottom-card {
  margin: 4px;
  padding: 1rem;
  .icon-localoffer {
    font-weight: 900;
  }
  span {
    margin-left: 0.3rem;
  }
  .site-info {
    padding: 0.3rem 1rem;
    line-height: 2;
    font-size: 1rem;

    .value {
      font-weight: 600;
    }
  }
}

.group {
  margin-left: 0.3rem;
  width: 100%;
  height: auto;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .img {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    margin-right: 10px;
  }
}
</style>